package com.afd.ozblip.activity;

import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.afd.ozblip.entity.ReviewEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.StringUtil;
import com.j256.ormlite.android.AndroidDatabaseConnection;
import com.j256.ormlite.dao.Dao;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

public class AddReviewActivity extends BaseActivity {

	/****************** 视图变量 **************************/
	private LinearLayout commonLeft;
	private LinearLayout commonRight;
	private RatingBar totalStarRb;
	private TextView ricPointTv;
	private TextView thrPointTv;
	private TextView envPointTv;
	private EditText businessPriceEt;
	private EditText reviewContentEt;
	/****************** 数据变量 **************************/
	private ReviewEntity draftReviewInfo;
	private String businessId;
	private String businessName;
	private float totalStar;
	private String ricPointStr;
	private String thrPointStr;
	private String envPointStr;
	private String businessPriceStr;
	private String reviewContentStr;
	private List<HashMap<String, Object>> markList;
	private OzBlipApplication myApp;
	private Dao<ReviewEntity, Integer> reviewDao;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_review);
		// 寻找视图
		findViews();
		// 设置监听
		setListeners();
		// 获取参数
		getBundle();
		// 设置视图
		setViews();
	}

	/**
	 * 寻找视图
	 */
	public void findViews() {
		// 初始化APP
		this.myApp = (OzBlipApplication) getApplication();
		try {
			this.reviewDao = myApp.getDBHelper().getDao(ReviewEntity.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		markList = new ArrayList<HashMap<String, Object>>();
		HashMap<String, Object> map1 = new HashMap<String, Object>();
		map1.put("key", "5");
		map1.put("value", "非常好");
		markList.add(map1);
		HashMap<String, Object> map2 = new HashMap<String, Object>();
		map2.put("key", "4");
		map2.put("value", "很好");
		markList.add(map2);
		HashMap<String, Object> map3 = new HashMap<String, Object>();
		map3.put("key", "3");
		map3.put("value", "好");
		markList.add(map3);
		HashMap<String, Object> map4 = new HashMap<String, Object>();
		map4.put("key", "2");
		map4.put("value", "一般");
		markList.add(map4);
		HashMap<String, Object> map5 = new HashMap<String, Object>();
		map5.put("key", "1");
		map5.put("value", "差");
		markList.add(map5);
		this.commonLeft = (LinearLayout) findViewById(R.id.ll_common_left);
		this.commonRight = (LinearLayout) findViewById(R.id.ll_common_right);
		this.totalStarRb = (RatingBar) findViewById(R.id.rb_add_review_star);
		this.ricPointTv = (TextView) findViewById(R.id.tv_add_review_kw);
		this.thrPointTv = (TextView) findViewById(R.id.tv_add_review_hj);
		this.envPointTv = (TextView) findViewById(R.id.tv_add_review_fw);
		this.businessPriceEt = (EditText) findViewById(R.id.et_add_review_price);
		this.reviewContentEt = (EditText) findViewById(R.id.et_add_review_content);
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {
		View.OnClickListener addReviewClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_common_left:
					Dialog alertDialog = new AlertDialog.Builder(
							AddReviewActivity.this)
							.setTitle("提示")
							.setMessage("是否保存到草稿箱")
							.setIcon(android.R.drawable.ic_menu_help)
							.setPositiveButton("确定",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											try {
												AndroidDatabaseConnection conn = new AndroidDatabaseConnection(
														myApp.getDBHelper()
																.getWritableDatabase(),
														true);
												reviewDao.setAutoCommit(conn,
														false);
												Savepoint point = conn
														.setSavePoint("a");
												ReviewEntity review = new ReviewEntity();
												review.setSellerId(businessId);
												review.setSellerName(businessName);
												review.setSellerStar(totalStarRb
														.getRating());
												if (ricPointTv.getTag() != null) {
													review.setKouwei(Integer
															.parseInt(ricPointTv
																	.getTag()
																	.toString()));
												}
												if (thrPointTv.getTag() != null) {
													review.setHuanjing(Integer
															.parseInt(thrPointTv
																	.getTag()
																	.toString()));
												}
												if (envPointTv.getTag() != null) {
													review.setFuwu(Integer
															.parseInt(envPointTv
																	.getTag()
																	.toString()));
												}
												review.setPrice(businessPriceEt
														.getText().toString());
												review.setReviewNaiyo(reviewContentEt
														.getText().toString());
												review.setReviewDate(StringUtil
														.getFormatData1(new Date()));
												reviewDao.create(review);
												conn.commit(null);
												reviewDao.commit(conn);
											} catch (Exception e) {
												e.printStackTrace();
											}
											finish();
										}
									})
							.setNegativeButton("取消",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											finish();
										}
									}).create();
					alertDialog.show();
					break;
				case R.id.ll_common_right:
					totalStar = totalStarRb.getRating();
					ricPointStr = ricPointTv.getText().toString();
					thrPointStr = thrPointTv.getText().toString();
					envPointStr = envPointTv.getText().toString();
					businessPriceStr = businessPriceEt.getText().toString();
					reviewContentStr = reviewContentEt.getText().toString();
					if (verifyData()) {
						requestAddReviewData();
					}
					break;
				case R.id.tv_add_review_kw:
					showListDialog(markList, ricPointTv);
					break;
				case R.id.tv_add_review_hj:
					showListDialog(markList, thrPointTv);
					break;
				case R.id.tv_add_review_fw:
					showListDialog(markList, envPointTv);
					break;
				default:
					break;
				}
			}
		};
		this.commonLeft.setOnClickListener(addReviewClick);
		this.commonRight.setOnClickListener(addReviewClick);
		this.ricPointTv.setOnClickListener(addReviewClick);
		this.thrPointTv.setOnClickListener(addReviewClick);
		this.envPointTv.setOnClickListener(addReviewClick);
	}

	/**
	 * 获取传递的参数
	 */
	private void getBundle() {
		Intent intent = getIntent();
		businessId = intent.getStringExtra("businessId");
		businessName = intent.getStringExtra("businessName");
		draftReviewInfo = (ReviewEntity) intent
				.getSerializableExtra("reviewInfo");
	}

	/**
	 * 设置视图
	 */
	private void setViews() {
		if (draftReviewInfo != null) {
			businessId = draftReviewInfo.getSellerId();
			businessName = draftReviewInfo.getSellerName();
			Float totalStar = draftReviewInfo.getSellerStar();
			if (totalStar != null) {
				totalStarRb.setRating(totalStar);
			}
			Integer kouwei = draftReviewInfo.getKouwei();
			if (kouwei != null && kouwei != 0) {
				ricPointTv.setText(markList.get(5 - kouwei).get("value")
						.toString());
				ricPointTv.setTag(kouwei);
			}
			Integer huanjing = draftReviewInfo.getHuanjing();
			if (huanjing != null && huanjing != 0) {
				thrPointTv.setText(markList.get(5 - huanjing).get("value")
						.toString());
				thrPointTv.setTag(huanjing);
			}
			Integer fuwu = draftReviewInfo.getFuwu();
			if (fuwu != null && fuwu != 0) {
				envPointTv.setText(markList.get(5 - fuwu).get("value")
						.toString());
				envPointTv.setTag(fuwu);
			}
			String price = draftReviewInfo.getPrice();
			if (!StringUtil.isNullOrEmpty(price)) {
				businessPriceEt.setText(price);
			}
			String content = draftReviewInfo.getReviewNaiyo();
			if (!StringUtil.isNullOrEmpty(content)) {
				reviewContentEt.setText(content);
			}

		}
	}

	/**
	 * 验证数据
	 */
	private boolean verifyData() {
		if (totalStar == 0) {
			showLongToast(this, "请选择评价分数！", true);
			return false;
		}
		if ("点击选择打分>>".equals(ricPointStr)) {
			showLongToast(this, "请为口味打分！", true);
			return false;
		}
		if ("点击选择打分>>".equals(thrPointStr)) {
			showLongToast(this, "请为环境打分！", true);
			return false;
		}
		if ("点击选择打分>>".equals(envPointStr)) {
			showLongToast(this, "请为口味打分！", true);
			return false;
		}
		if (StringUtil.isNullOrEmpty(reviewContentStr)) {
			showLongToast(this, "请输入点评内容！", true);
			return false;
		}

		return true;
	}

	/**
	 * 获取上传图片数据
	 */
	private void requestAddReviewData() {
		if (StringUtil.isNullOrEmpty(businessId)) {
			return;
		}
		if (commonUserInfo == null) {
			return;
		}
		AsyncLoadData ald = new AsyncLoadData(this, "提交中...",
				new AsyncAction() {

					@Override
					public void doLoad() throws Exception {
						// 获取提交参数
						Map<String, Object> addReviewParamMap = new HashMap<String, Object>();
						addReviewParamMap.put("sellerId", businessId);
						addReviewParamMap.put("sellerStar", totalStar);
						addReviewParamMap.put("ricPoint", ricPointTv.getTag());
						addReviewParamMap.put("thrPoint", thrPointTv.getTag());
						addReviewParamMap.put("envPoint", envPointTv.getTag());
						addReviewParamMap.put("price", businessPriceStr);
						addReviewParamMap.put("reivewNaiyo", reviewContentStr);
						addReviewParamMap.put("userId",
								commonUserInfo.getUserId());
						addReviewParamMap.put("language", commonLanguage);
						// 发送请求
						byte[] commentItemList = HttpUtil.requestByPost(
								AddReviewActivity.this,
								Constants.ADD_REVIEW_API, addReviewParamMap);
						if (commentItemList != null) {

						}
					}

					@Override
					public void loadEnd() throws Exception {
						showShortToast(AddReviewActivity.this, "温馨提示：点评成功！");
						finish();
					}

				});
		ald.execute(0);

	}
}